package cn.xuan.scan.dao.query.param.impl;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.xuan.scan.dao.query.param.CommonPersistContext;

public class CommonPersistContextImpl implements CommonPersistContext {
	private static final Logger logger = LoggerFactory.getLogger(CommonPersistContextImpl.class);
	ApplicationContext applicationContext ;
	
	public Object getDaoByClassName(String _className) {
		String daoName = _className.substring(0, 1).toLowerCase() + _className.substring(1, _className.length())
				+ "DAO";
		logger.info("getDaoByClassName: " + daoName);
		if(applicationContext == null) {
			applicationContext = getApplicationContext();
		}
		
		if(applicationContext == null) {
			return null;
		}else {
			return applicationContext.getBean(_className);
		}
		 
	}
	
	private ApplicationContext getApplicationContext() {
		// Spring中获取ServletContext对象，普通类中可以这样获取
		ServletContext sc = ContextLoader.getCurrentWebApplicationContext().getServletContext(); 
		// servlet中可以这样获取,方法比较多
//		ServletContext sc = request.getServletContext():ServletContext sc = servletConfig.getServletContext();  
		//servletConfig可以在servlet的init(ServletConfig config)方法中获取得到 
		/* 需要传入一个参数ServletContext对象, 获取方法在上面 */
		// 这种方法 获取失败时抛出异常
//		ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
		// 这种方法 获取失败时返回null
		ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
		return ac;
		
	}
}
